import  os
from fastapi import Request,APIRouter
from starlette.responses import StreamingResponse

from config.docxs import ZIP_FILE_PATH
from func.docxs.word import *
from func.file.Type import FileTypeChecker
from func.file.zip_tempfile_localfile import compress_files_to_zip
from func.date import get_str_date_uniform
docxs=APIRouter(prefix="/docxs",tags=["docxs"])

def export_docx(formdata,images):
    title=formdata["title"]
    if not title:
        title="无题"
    content=formdata["content"]
    date=formdata["date"]
    doc=InitDocument(title+'.docx','user_resource/middle_station/')
    P,LEN=doc.judge_paragraphs_len(content)
    doc.add_header(title,style_name='Heading1')
    doc.add_paragraph(date,style_name='date')
    for i in P:
        doc.add_paragraph(i,style_name='Normal')
    if images :
        for i in images:
                doc.add_image(i,width=2, height=2, style_name='Normal')
    doc.save()
    return doc.root_path+title+'.docx'
@docxs.get('/deal/export')
async def deal_get_export(name:str):
    file_path = os.path.join(ZIP_FILE_PATH, name)
    file_stream=open(file_path,'rb')
    return StreamingResponse(file_stream, media_type='application/zip')

@docxs.post("/deal/export")
async  def deal_export(request: Request):
    try:
        formdata = await request.form()
        title = formdata.get("title","无题")
        files=[]
        images= []
        videos=[]
        if len(formdata) - 3:
            for i in range(len(formdata) - 3):
                pool_file=formdata[f'file{i}'].file
                files.append(pool_file)
                if FileTypeChecker().is_image(pool_file):
                    images.append(pool_file)
                else:
                    videos.append(pool_file)
        path=export_docx(formdata,images)
        name=get_str_date_uniform()
        compress_files_to_zip(spooled_file=files,local_file_path=path,zip_file_path=f"{ZIP_FILE_PATH}/{name}.zip")
        
    except Exception as e:
        return 0
    return {
        'title':title+'.zip',
        'name':name+'.zip'
    }



